import SwiftUI

#if os(iOS) || os(tvOS)
import UIKit
#endif

#if os(tvOS)
import TVUIKit
#endif

#if os(tvOS)
/// tvOS 滚动控制器
@available(tvOS 13.0, *)
class TVScrollController: ObservableObject {
    @Published var scrollOffset: CGFloat = 0
    @Published var isScrolling: Bool = false
    
    private var scrollView: UIScrollView?
    private let scrollStep: CGFloat = 300 // 每次滚动的步长
    private var consecutiveUpPresses: Int = 0
    private var lastUpPressTime: Date = Date()
    private var focusManager: TVFocusManager?
    private var currentPageIndex: Int = 0
    
    func setFocusManager(_ focusManager: TVFocusManager) {
        self.focusManager = focusManager
    }
    
    func setCurrentPageIndex(_ index: Int) {
        self.currentPageIndex = index
    }
    
    func setScrollView(_ scrollView: UIScrollView) {
        self.scrollView = scrollView
    }
    
    func handleDirectionalInput(_ direction: Direction) {
        guard let scrollView = scrollView else { 
            print("TVScrollController: scrollView 为 nil")
            return 
        }
        
        print("TVScrollController: 处理方向输入 - \(direction)")
        
        switch direction {
        case .up:
            scrollUp()
        case .down:
            scrollDown()
        case .left, .right:
            break // 左右键不处理滚动
        }
    }
    
    private func scrollUp() {
        guard let scrollView = scrollView else { return }
        
        let currentOffset = scrollView.contentOffset.y
        let maxOffset = max(0, scrollView.contentSize.height - scrollView.bounds.height)
        
        // 检查是否应该强制滚动到顶部
        let timeSinceLastPress = Date().timeIntervalSince(lastUpPressTime)
        if currentOffset <= 100 || (consecutiveUpPresses >= 2 && timeSinceLastPress <= 1.0) {
            // 强制滚动到顶部
            scrollView.setContentOffset(CGPoint(x: 0, y: 0), animated: true)
            DispatchQueue.main.async {
                self.isScrolling = true
            }
            DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
                self.isScrolling = false
                // 滚动到顶部后，触发焦点转移到导航
                print("TVScrollController: 滚动到顶部，请求导航焦点，页面索引: \(self.currentPageIndex)")
                // 使用焦点管理器的当前页面索引，如果没有则使用本地索引
                let targetIndex = self.focusManager?.currentPageIndex ?? self.currentPageIndex
                self.focusManager?.requestNavigationFocus(targetIndex: targetIndex)
            }
            consecutiveUpPresses = 0
        } else {
            // 正常向上滚动
            let newOffset = max(0, currentOffset - scrollStep)
            scrollView.setContentOffset(CGPoint(x: 0, y: newOffset), animated: true)
            DispatchQueue.main.async {
                self.isScrolling = true
            }
            DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
                self.isScrolling = false
            }
            consecutiveUpPresses += 1
        }
        
        lastUpPressTime = Date()
    }
    
    private func scrollDown() {
        guard let scrollView = scrollView else { 
            print("TVScrollController: scrollDown - scrollView 为 nil")
            return 
        }
        
        let currentOffset = scrollView.contentOffset.y
        let maxOffset = max(0, scrollView.contentSize.height - scrollView.bounds.height)
        
        print("TVScrollController: scrollDown - 当前偏移: \(currentOffset), 最大偏移: \(maxOffset), 内容高度: \(scrollView.contentSize.height), 视图高度: \(scrollView.bounds.height)")
        
        // 检查是否应该强制滚动到底部
        if currentOffset >= maxOffset - 100 {
            // 强制滚动到底部
            print("TVScrollController: scrollDown - 滚动到底部")
            scrollView.setContentOffset(CGPoint(x: 0, y: maxOffset), animated: true)
            DispatchQueue.main.async {
                self.isScrolling = true
            }
            DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
                self.isScrolling = false
            }
        } else {
            // 正常向下滚动
            let newOffset = min(maxOffset, currentOffset + scrollStep)
            print("TVScrollController: scrollDown - 滚动到新偏移: \(newOffset)")
            scrollView.setContentOffset(CGPoint(x: 0, y: newOffset), animated: true)
            DispatchQueue.main.async {
                self.isScrolling = true
            }
            DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
                self.isScrolling = false
            }
        }
        
        consecutiveUpPresses = 0 // 重置向上按键计数
    }
    
    func scrollToTop() {
        guard let scrollView = scrollView else { return }
        
        scrollView.setContentOffset(CGPoint(x: 0, y: 0), animated: true)
        DispatchQueue.main.async {
            self.isScrolling = true
        }
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
            self.isScrolling = false
        }
    }
    
    func scrollToBottom() {
        guard let scrollView = scrollView else { return }
        
        let maxOffset = max(0, scrollView.contentSize.height - scrollView.bounds.height)
        scrollView.setContentOffset(CGPoint(x: 0, y: maxOffset), animated: true)
        DispatchQueue.main.async {
            self.isScrolling = true
        }
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
            self.isScrolling = false
        }
    }
    
}

/// 滚动方向枚举
enum Direction {
    case up, down, left, right
}

/// tvOS 滚动视图包装器
@available(tvOS 13.0, *)
struct TVScrollViewRepresentable: UIViewRepresentable {
    let content: AnyView
    let scrollController: TVScrollController
    
    func makeUIView(context: Context) -> UIScrollView {
        let scrollView = UIScrollView()
        scrollView.showsVerticalScrollIndicator = false
        scrollView.showsHorizontalScrollIndicator = false
        scrollView.bounces = true
        scrollView.alwaysBounceVertical = true
        
        // 创建内容视图
        let hostingController = UIHostingController(rootView: content)
        hostingController.view.translatesAutoresizingMaskIntoConstraints = false
        
        scrollView.addSubview(hostingController.view)
        
        // 修复约束设置，确保内容可以正确滚动
        NSLayoutConstraint.activate([
            hostingController.view.topAnchor.constraint(equalTo: scrollView.topAnchor),
            hostingController.view.leadingAnchor.constraint(equalTo: scrollView.leadingAnchor),
            hostingController.view.trailingAnchor.constraint(equalTo: scrollView.trailingAnchor),
            hostingController.view.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor),
            hostingController.view.widthAnchor.constraint(equalTo: scrollView.widthAnchor),
            // 确保内容高度至少等于滚动视图高度，这样内容才能滚动
            hostingController.view.heightAnchor.constraint(greaterThanOrEqualTo: scrollView.heightAnchor)
        ])
        
        scrollController.setScrollView(scrollView)
        
        return scrollView
    }
    
    func updateUIView(_ uiView: UIScrollView, context: Context) {
        // 更新视图内容
    }
}
#endif

/// 跨平台滚动视图包装器
@available(iOS 13.0, tvOS 13.0, macOS 10.15, *)
struct TVScrollViewWrapper<Content: View>: View {
    let content: Content
    let pageIndex: Int
    #if os(tvOS)
    @StateObject private var scrollController = TVScrollController()
    @FocusState private var isFocused: Bool
    #endif
    @EnvironmentObject var focusManager: TVFocusManager
    
    init(pageIndex: Int, @ViewBuilder content: () -> Content) {
        self.pageIndex = pageIndex
        self.content = content()
    }
    
    var body: some View {
        #if os(tvOS)
        TVScrollViewRepresentable(content: AnyView(content), scrollController: scrollController)
            .focusable(true)
            .focused($isFocused)
            .onKeyPress(.upArrow) {
                print("TVScrollViewWrapper: 检测到向上箭头键")
                scrollController.handleDirectionalInput(.up)
                return .handled
            }
            .onKeyPress(.downArrow) {
                print("TVScrollViewWrapper: 检测到向下箭头键")
                scrollController.handleDirectionalInput(.down)
                return .handled
            }
            .onAppear {
                scrollController.setFocusManager(focusManager)
                scrollController.setCurrentPageIndex(pageIndex)
            }
            .onChange(of: focusManager.shouldFocusNavigation) { shouldFocus in
                if shouldFocus {
                    // 当需要转移焦点到导航时，取消当前焦点
                    isFocused = false
                }
            }
            .onChange(of: focusManager.currentFocusArea) { focusArea in
                print("TVScrollViewWrapper: 焦点区域改变为: \(focusArea)，当前页面: \(pageIndex)")
                if focusArea == .content && focusManager.currentPageIndex == pageIndex {
                    // 当焦点管理器请求内容焦点且当前页面匹配时，设置焦点到滚动视图
                    print("TVScrollViewWrapper: 设置内容焦点")
                    isFocused = true
                }
            }
            .onChange(of: focusManager.currentPageIndex) { pageIndex in
                // 当页面索引改变时，如果当前页面匹配，确保焦点在内容区域
                if pageIndex == self.pageIndex {
                    isFocused = true
                }
            }
        #else
        // 在非tvOS平台上，直接显示内容
        content
        #endif
    }
}
